package com.next

import grails.validation.ValidationException
import static org.springframework.http.HttpStatus.*
import org.springframework.security.access.annotation.Secured

@Secured(['ROLE_ADMINISTRATOR', 'ROLE_CUSTOMER_SERVICE_REPRESENTATIVE', 'ROLE_ACCOUNT_MANAGER', 'ROLE_COMPANY_ADMINISTRATOR', 'ROLE_GENERAL_RISK_MANAGER', 'ROLE_BRANCH_GENERAL_MANAGER', 'ROLE_BRANCH_OFFICE_RISK_MANAGER', 'ROLE_HEAD_OFFICE_RISK_MANAGER', 'ROLE_GENERAL_MANAGER', 'ROLE_CRO', 'ROLE_CEO', 'ROLE_POST_LOAN_MANAGER', 'ROLE_BRANCH_OFFICE_POST_LOAN_MANAGER'])
class VehicleController
{

    // VehicleService vehicleService
    def vehicleService
    def mailService
    def propertyValuationProviderService
    def springSecurityService

    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]

    def index(Integer max)
    {
        params.max = Math.min(max ?: 10, 100)
        respond vehicleService.list(params), model: [vehicleCount: vehicleService.count()]
    }

    def show(Long id)
    {
        respond vehicleService.get(id)
    }

    def create()
    {
        respond new Vehicle(params)
    }

    def save(Vehicle vehicle)
    {
        if (vehicle == null)
        {
            notFound()
            return
        }

        try
        {
            def username = springSecurityService.getPrincipal().username
            def user = User.findByUsername(username)
            vehicle.createdBy = user
            vehicle.modifiedBy = user

            vehicleService.save(vehicle)
        }
        catch (ValidationException e)
        {
            respond vehicle.errors, view: 'create'
            return
        }

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.created.message', args: [message(code: 'vehicle.label', default: 'Vehicle'), vehicle.id])
                // redirect vehicle
                redirect(controller: "opportunity", action: "show", params: [id: vehicle?.opportunity?.id])
            }
            '*' { respond vehicle, [status: CREATED] }
        }
    }

    def edit(Long id)
    {
        respond vehicleService.get(id)
    }

    def update(Vehicle vehicle)
    {
        if (vehicle == null)
        {
            notFound()
            return
        }

        try
        {
            def username = springSecurityService.getPrincipal().username
            def user = User.findByUsername(username)
            vehicle.modifiedBy = user

            vehicleService.save(vehicle)
        }
        catch (ValidationException e)
        {
            respond vehicle.errors, view: 'edit'
            return
        }

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.updated.message', args: [message(code: 'vehicle.label', default: 'Vehicle'), vehicle.id])
                // redirect vehicle
                redirect(controller: "opportunity", action: "show", params: [id: vehicle?.opportunity?.id])
            }
            '*' { respond vehicle, [status: OK] }
        }
    }

    def delete(Long id)
    {
        if (id == null)
        {
            notFound()
            return
        }

        vehicleService.delete(id)

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.deleted.message', args: [message(code: 'vehicle.label', default: 'Vehicle'), id])
                redirect action: "index", method: "GET"
            }
            '*' { render status: NO_CONTENT }
        }
    }

    protected void notFound()
    {
        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.not.found.message', args: [message(code: 'vehicle.label', default: 'Vehicle'), params.id])
                redirect action: "index", method: "GET"
            }
            '*' { render status: NOT_FOUND }
        }
    }

    def searchVehicle()
    {
        params.max = Math.min(params.max ? params.max.toInteger() : 10, 100)
        params.offset = params.offset ? params.offset.toInteger() : 0;

        def max = params.max
        def offset = params.offset

        String sql = "from Vehicle as o where 1 = 1"
        def projectName = params["projectName"]
        if (projectName)
        {
            sql += " and o.projectName like '%${projectName}%'"
        }

        def externalId = params["externalId"]
        if (externalId)
        {
            sql += " and o.externalId = '${externalId}'"
        }

        def serialNumber = params["serialNumber"]
        if (serialNumber)
        {
            sql += " and o.opportunity.serialNumber = '${serialNumber}'"
        }

        def startTime = params["startTime"]
        def endTime = params["endTime"]
        if (startTime && endTime)
        {
            sql += " and o.createdDate between '${startTime}' and '${endTime}'"
        }

        def city = params["city"]
        if (city && city != "null")
        {
            sql += " and o.city.name = '${city}'"
        }

        sql += " order by o.createdDate desc"
        println sql
        def list = House.findAll(sql, [max: max, offset: offset])
        def list1 = House.findAll(sql)
        Integer count = list1.size()

        respond list, model: [vehicleCount: count, params: params], view: 'index'
    }
}
